package pzhu.web;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

public class demo {

	public static void main(String[] args) throws InterruptedException, IOException {
		int page = 1, i = 0;
		while (page <= 2) {
			i = 0;
			// 1.生成httpclient，相当于该打开一个浏览器
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = null;
			// 2.创建get请求，相当于在浏览器地址栏输入 网址
			HttpGet request = new HttpGet("http://www.haomahao.com/shop.asp?Page=" + page);
			try {
				// 3.执行get请求，相当于在输入地址栏后敲回车键
				response = httpClient.execute(request);
				// 4.判断响应状态为200，进行处理
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					// 5.获取响应内容
					HttpEntity httpEntity = response.getEntity();
					String html = EntityUtils.toString(httpEntity, "gb2312");
					// System.out.println(html);
					org.jsoup.nodes.Document document = Jsoup.parse(html);
					Elements number = document.select("div.content div.shop_content td.bar a");
					Elements area = document.select("div.content div.shop_content td.grord");
					Elements balance = document.select("div.content div.shop_content td.red");
					Elements price = document.select("div.content div.shop_content td.redd");
					Elements addr = document.select("div.content div.shop_content td.bar a");
					while (i <= 41) {
						System.out.println("电话号码：" + number.get(i).text() + "\t所属地：" + area.get(i).text() + "\n含话费："
								+ balance.get(i).text() + "\t购买价格：" + price.get(i).text()
								+ "\n购买地址：http://www.haomahao.com/" + addr.get(i).attr("href"));
						i++;
					}
				} else {
					// 如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
					System.out.println("返回状态不是200");
					System.out.println(EntityUtils.toString(response.getEntity(), "gb2312"));
				}

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// 6.关闭
				HttpClientUtils.closeQuietly(response);
				HttpClientUtils.closeQuietly(httpClient);
			}
			System.out.println("\n**************  第  " + page + "  页  **************\n");
			page++;
		}
		System.out.println("共计：" + i * page + "个号码");
	}
}